package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 2018/7/17
 */
class MissionDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  type MyRow = MissionRow
  val table = Mission

  def selectOp(userId: Int, kind: String, missionName: String): Future[Option[MissionRow]] = db.run(Mission.
    filter(_.userId === userId).filter(_.kind === kind).filter(_.missionName === missionName).result.headOption)

  def selectOp(userId: Int, missionName: String): Future[Option[MissionRow]] = db.run(Mission.
    filter(_.userId === userId).filter(_.missionName === missionName).result.headOption)

  def select(userId: Int, kind: String, missionName: String) = db.run(Mission.
    filter(_.userId === userId).filter(_.kind === kind).filter(_.missionName === missionName).result.head)

  def select(userId: Int, missionName: String) = db.run(Mission.
    filter(_.userId === userId).filter(_.missionName === missionName).result.head)

  def select(missionId: Int) = db.run(Mission.
    filter(_.id === missionId).result.head)

  def insert(row: MissionRow): Future[Unit] = db.run(Mission += row).map(_ => ())

  def update(row: MissionRow): Future[Unit] = db.run(Mission.filter(_.id === row.id).update(row)).map(_ => ())

  def selectAll(userId: Int) = db.run(Mission.
    filter(x => x.userId === userId).sortBy(_.id.desc).result)

  def selectAllKind(userId: Int) = db.run(table.
    filter(x => x.userId === userId).map(_.kind).distinct.result)

  def selectAll(userId: Int, kind: String) = db.run(Mission.
    filter(x => x.userId === userId).filter(_.kind === kind).sortBy(_.id.desc).result)

  def selectAll(userId: Int, kinds: Seq[String]) = db.run(Mission.
    filter(x => x.userId === userId).filter(_.kind.inSetBind(kinds)).sortBy(_.id.desc).result)

  def selectAll(state: String) = db.run(Mission.filter(_.state === state).
    sortBy(_.id.desc).result)

  def selectAll(ids: List[Int]) = db.run(Mission.filter(_.id.inSetBind(ids))
    .result)

  def selectAll(userId: Int, missionNames: List[String]) = db.run(table.
    filter(_.userId === userId).filter(_.missionName.inSetBind(missionNames)).result)

  def delete(userId: Int, missionId: Int): Future[Unit] = db.run(Mission.filter(_.userId === userId).
    filter(_.id === missionId).delete).map(_ => ())

  def deletes(ids: List[Int]): Future[Unit] = db.run(Mission.filter(_.id.inSetBind(ids)).delete).map(_ => ())

  def selectSingleColumn(columnName: String) = db.run(table.map { x =>
    columnName match {
      case "kind" => x.kind
      case "state" => x.state
    }
  }.distinct.result)


}
